package com.zzl.study.nacos.actuator;

import com.alibaba.nacos.api.naming.NamingService;
import com.zzl.study.nacos.NacosServiceMultiManager;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;

import java.util.List;

/**
 * Nacos多注册中心服务发现健康检查指标
 *
 * @author: zhangzl
 * @date: 2025/7/16 20:09
 * @version: 1.0
 */
public class NacosMultiDiscoveryHealthIndicator extends AbstractHealthIndicator {

    /**
     * 服务状态：UP
     */
    private static final String STATUS_UP = "UP";

    /**
     * 服务状态：DOWN
     */
    private static final String STATUS_DOWN = "DOWN";

    /**
     * Nacos多注册中心服务管理器
     */
    private final NacosServiceMultiManager nacosServiceMultiManager;

    /**
     * 构造方法
     *
     * @param nacosServiceMultiManager Nacos多注册中心服务管理器
     */
    public NacosMultiDiscoveryHealthIndicator(NacosServiceMultiManager nacosServiceMultiManager) {
        this.nacosServiceMultiManager = nacosServiceMultiManager;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) throws Exception {
        List<NamingService> namingServiceList = this.nacosServiceMultiManager.getNamingServices();
        boolean up = namingServiceList.stream().anyMatch(namingService -> STATUS_UP.equalsIgnoreCase(namingService.getServerStatus()));
        String status = up ? STATUS_UP : STATUS_DOWN;
        builder.status(status);
        switch (status) {
            case STATUS_UP -> builder.up();
            case STATUS_DOWN -> builder.down();
            default -> builder.unknown();
        }
    }

}
